package com.fc.redap.process;

import com.fc.redap.dtos.ResponseJson;
import com.fc.redap.exception.ResponseException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ResponseExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(ResponseException.class)
	public ResponseJson handleResponseException(ResponseException e){
		return ResponseJson.error(e.getCode(), e.getMsg());
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public ResponseJson handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return ResponseJson.error("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public ResponseJson handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
		return ResponseJson.error("没有权限，请联系管理员授权");
	}

	@ExceptionHandler(AuthenticationException.class)
	public ResponseJson handleAuthorizationException(AuthenticationException e){
		logger.error(e.getMessage(), e);
		return ResponseJson.error(ResponseJson.CODE_403,e.getMessage());
	}

	@ExceptionHandler(ExcessiveAttemptsException.class)
	public ResponseJson handleExcessiveAttemptsException(ExcessiveAttemptsException e){
		logger.error(e.getMessage(), e);
		return ResponseJson.error(ResponseJson.CODE_403,e.getMessage());
	}

	@ExceptionHandler(Exception.class)
	public ResponseJson handleException(Exception e){
		logger.error(e.getMessage(), e);
		return ResponseJson.error("服务器内部错误, 请稍后重试!");
	}
}
